package com.mall.order.mq.order;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author: JK
 * @Date: create in 2021/7/23 17:34
 */
@Slf4j
@Component
public class DelayOrderProducer {

    private DefaultMQProducer producer;

    // 加上@PostConstruct注解，spring会自动调用该方法
    @PostConstruct
    public void init() {
        producer = new DefaultMQProducer("delay_order_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            log.info("DelayOrderProducer#init producer启动失败: " + e);
            e.printStackTrace();
        }
    }

    public Boolean sendOrderDelayMessage(String orderId) {
        Message message = new Message("delay_order_cancel", orderId.getBytes(StandardCharsets.UTF_8));
        // 延迟时间：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 延迟级别：1  2  3   4   5  6  7  8  9  10 11 12 13 14  15  16  17 18
        message.setDelayTimeLevel(5);
        try {
            SendResult send = producer.send(message);
            if (SendStatus.SEND_OK.equals(send.getSendStatus())) {
                // 日志记录发送结果
                log.info("DelayOrderProducer#sendOrderDelayMessage Provider成功发送订单延迟消息");
                return true;
            }

        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            // 日志输出异常信息
            log.info("DelayOrderProducer#sendOrderDelayMessage Occur Exception: " + e);
            e.printStackTrace();
        }

        // 日志记录发送失败
        log.info("DelayOrderProducer#sendOrderDelayMessage 发送订单延迟消息失败");

        return false;
    }
}
